package com.burgeon.backend.SHOP.service.Impl;

import com.burgeon.backend.SHOP.entity.BirthdayConfiguration;
import com.burgeon.backend.SHOP.entity.BirthdayCouponRecord;
import com.burgeon.backend.SHOP.entity.CouponType;
import com.burgeon.backend.SHOP.entity.Goods;
import com.burgeon.backend.SHOP.mappers.AppCouponMapper;
import com.burgeon.backend.SHOP.mappers.BirthdayCouponMapper;
import com.burgeon.backend.SHOP.rest.CreateAppCoupon;
import com.burgeon.backend.SHOP.service.AppTemplateService;
import com.burgeon.backend.SHOP.service.BirthdayCouponService;
import com.burgeon.backend.SHOP.service.ex.ErrorDataExceptionApp;
import com.burgeon.backend.SHOP.service.ex.InsertExceptionApp;
import com.burgeon.backend.entity.Coupon;
import com.burgeon.backend.entity.Info;
import com.burgeon.backend.entity.User;
import com.burgeon.backend.mappers.AccountMapper;
import com.burgeon.backend.mappers.CouponRestrictMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class BirthdayCouponServiceImpl implements BirthdayCouponService {

    @Autowired
    private BirthdayCouponMapper birthdayCouponMapper;
    @Autowired
    private AppCouponMapper appCouponMapper;
    @Autowired
    private CouponRestrictMapper couponRestrictMapper;
    @Autowired
    private AccountMapper accountMapper;
    @Autowired
    private AppTemplateService appTemplateService;


    //生日优惠券及是否符合生日购买积分商品的要求
    @Override
    public CouponType findBirthdayCoupon(String token, String uid) throws ParseException {

        try {

            BirthdayConfiguration birthdayConfiguration = birthdayCouponMapper.findBirthdayCoupon(token);

            CouponType couponType = birthdayCouponMapper.findCouponType(birthdayConfiguration.getCouponTypeId());

            //查看今年是否领取过生日优惠券
            BirthdayCouponRecord BirthdayRecord = birthdayCouponMapper.findBirthdayRecord(uid,token);
            if (BirthdayRecord != null){
                couponType.setIsReceive("Y");//领取过
            }else {
                couponType.setIsReceive("N");//未领取
            }

            //领取限制
            SimpleDateFormat mDay = new SimpleDateFormat("yyyyMMdd");
            Date date = new Date();
            String today = mDay.format(date);
            //截取当前时间的月份，判断当月使用
            String nowMonth = today.substring(4, 6);

            //获取用户生日
            String userBirthday = birthdayCouponMapper.findUserBirthday(uid,token);
            String ym = mDay.format(mDay.parse(userBirthday));
            String userMonth = ym.substring(4, 6);//截取月份，判断当月使用

            //当前日期
            Calendar nowDay = Calendar.getInstance();
            Date nowDayTime = mDay.parse(mDay.format(date));
            nowDay.setTime(nowDayTime);

            //前七天获取结束日期 （即生日当天）
            Calendar endDay = Calendar.getInstance();
            String endMd = userBirthday.substring(4, 8);
            String nowY = today.substring(0, 4);
            //拼接成当前的年月日，因为after()，before()是按年月日比较
            String endNewTime = nowY + endMd;
            Date endDayTime = mDay.parse(endNewTime);
            endDay.setTime(endDayTime);

            if (birthdayConfiguration.getGetWay().equals("M")){//当月
                if(!nowMonth.equals(userMonth)){
                    couponType.setIsBuy("N");
                }else {
                    couponType.setIsBuy("Y");
                }
            }else if (birthdayConfiguration.getGetWay().equals("QW")){//前7天

                //获取前7天的日期
                Calendar beginDay = Calendar.getInstance();
                beginDay.setTime(mDay.parse(endNewTime));
                beginDay.set(Calendar.DATE, beginDay.get(Calendar.DATE) - 8);
                //after(),before()是大于小于，没有等于，所以多算一天
                endDay.set(Calendar.DATE,endDay.get(Calendar.DATE) + 1);

                if(nowDay.after(beginDay) && nowDay.before(endDay)){
                    couponType.setIsBuy("Y");
                }else {
                    couponType.setIsBuy("N");
                }
            }else if (birthdayConfiguration.getGetWay().equals("HW")){//后7天
                //获取后七天的日期
                Calendar beginDay = Calendar.getInstance();
                beginDay.setTime(mDay.parse(endNewTime));
                beginDay.set(Calendar.DATE, beginDay.get(Calendar.DATE) + 8);

                endDay.set(Calendar.DATE,endDay.get(Calendar.DATE) - 1);

                if(nowDay.after(endDay) && nowDay.before(beginDay)){
                    couponType.setIsBuy("Y");
                }else {
                    couponType.setIsBuy("N");
                }
            }else {
                couponType.setIsBuy("N");
            }
            return couponType;
        }catch (Exception e){
            e.printStackTrace();
            return null;
        }
    }

    //推荐商品
    @Override
    public List<Goods> recommendedGoods(String token, String logo, String flag) {
        List<Goods> data = birthdayCouponMapper.recommendedGoods(token,logo,flag);
        System.out.println("logo="+logo);
        System.out.println("flag="+flag);
        return data;
    }

    //商品搜索
    @Override
    public List<Goods> findGoodsData(String message, String token) {
        List<Goods> data  = birthdayCouponMapper.findGoodsData(message,token);
        return data;
    }

    @Override
    public void getBirthdayCoupon(String cid, String uid, String token, String phone, String openid) throws InsertExceptionApp, ParseException {

        String getTime = birthdayCouponMapper.findRecord(token,uid);//获取领取记录时间
        System.err.println(getTime);
        //领取限制
        SimpleDateFormat mDay = new SimpleDateFormat("yyyyMMdd");
        Date date = new Date();
        String today = mDay.format(date);
        //截取当前时间的月份，判断当月使用
        String nowMonth = today.substring(4, 6);
        //截取年，判断今年是否领取过
        String year = today.substring(0,4);

        if (getTime != null ){//判断是否领取过
            String getTimeYear = mDay.format(mDay.parse(getTime)).substring(0,4);
            if (year.equals(getTimeYear)){
                throw new InsertExceptionApp("已经领取过了，请尽快使用哦");
            }
        }else {
            BirthdayConfiguration birthdayConfiguration = birthdayCouponMapper.findBirthdayCoupon(token);

            //获取用户生日
            String userBirthday = birthdayCouponMapper.findUserBirthday(uid,token);
            String ym = mDay.format(mDay.parse(userBirthday));
            String userMonth = ym.substring(4, 6);//截取月份，判断当月使用

            //当前日期
            Calendar nowDay = Calendar.getInstance();
            Date nowDayTime = mDay.parse(mDay.format(date));
            nowDay.setTime(nowDayTime);

            //前七天获取结束日期 / 后七天的开始日期（即生日当天）
            Calendar endDay = Calendar.getInstance();
            String endMd = userBirthday.substring(4, 8);
            String nowY = today.substring(0, 4);
            //拼接成当前的年月日，因为after()，before()是按年月日比较
            String endNewTime = nowY + endMd;
            Date endDayTime = mDay.parse(endNewTime);
            endDay.setTime(endDayTime);

            if(birthdayConfiguration.getGetWay().equals("M")){//当月
                if(!nowMonth.equals(userMonth)){
                    throw new InsertExceptionApp("请在生日当月再来领取哦");
                }else {
                    createBirthdayCoupon(cid,uid,phone,openid,token);
                }
            }else if (birthdayConfiguration.getGetWay().equals("QW")){//前七天

                //获取前七天的日期
                Calendar beginDay = Calendar.getInstance();
                beginDay.setTime(mDay.parse(endNewTime));
                beginDay.set(Calendar.DATE, beginDay.get(Calendar.DATE) - 8);
                //after(),before()是大于小于，没有等于，所以多算一天
                endDay.set(Calendar.DATE,endDay.get(Calendar.DATE) + 1);

                if(nowDay.after(beginDay) && nowDay.before(endDay)){
                    createBirthdayCoupon(cid,uid,phone,openid,token);
                }else {
                    throw new InsertExceptionApp("抱歉，不在领取时间内，生日前七天才可以领取哦");
                }
            }else if (birthdayConfiguration.getGetWay().equals("HW")){//后七天
                //获取后七天的日期
                Calendar beginDay = Calendar.getInstance();
                beginDay.setTime(mDay.parse(endNewTime));
                beginDay.set(Calendar.DATE, beginDay.get(Calendar.DATE) + 8);

                endDay.set(Calendar.DATE,endDay.get(Calendar.DATE) - 1);

                if(nowDay.after(endDay) && nowDay.before(beginDay)){
                    createBirthdayCoupon(cid,uid,phone,openid,token);
                }else {
                    throw new InsertExceptionApp("抱歉，不在领取时间内，生日后七天才可以领取哦");
                }
            }else{
                throw new InsertExceptionApp("开小差了，稍后再试");
            }
        }

    }

    @Override
    public void sendBirthdayNotice(String token) throws ParseException {
        BirthdayConfiguration birthdayConfiguration = birthdayCouponMapper.findBirthdayCoupon(token);//查看开启的生日好礼活动
        if(birthdayConfiguration == null) {//为空结束程序
            System.exit(0);
        }
        List<User> userInfo = birthdayCouponMapper.findUserInfo(token);

        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        Date today = new Date();
        String todayString = sdf.format(today);
        String todayMonth = todayString.substring(4,8);

        for (User user:userInfo) {
            Calendar calendar = Calendar.getInstance();

            calendar.setTime(sdf.parse(user.getBirthday()));
            calendar.set(Calendar.DATE,calendar.get(Calendar.DATE) - 7);
            String birthdayTime = sdf.format(calendar.getTime());
            String monthDay = birthdayTime.substring(4, 8);

            if(!todayMonth.equals(monthDay)){
                continue;
            }

            appTemplateService.sendBirthdayNotice(user.getOpenid(),token,user.getPhone(),user.getName());

        }
    }

    //创建生日礼券
    private void createBirthdayCoupon(String cid, String uid, String phone, String openid, String token) throws ErrorDataExceptionApp {

        String scene = "1";//没错
        List<String> goodsCode = new ArrayList<String>();
        List<String> storeCode = new ArrayList<String>();

        CouponType couponType = appCouponMapper.findCouponTypeById(cid);
        if (couponType!=null){
            scene = couponType.getScene();
            if (couponType.getRestrictStore().equals("Y")){
                storeCode = couponRestrictMapper.getCouponTypeRestrictStore(couponType.getId());
            }
            if (couponType.getRestrictProduct().equals("Y")){
                goodsCode = couponRestrictMapper.getCouponTypeRestrictProduct(couponType.getId());
            }
        }

        String code = create_nonce_str().replace("-", "").trim().substring(22, 32);

        //SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        //SimpleDateFormat sssdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        SimpleDateFormat ssdf = new SimpleDateFormat("yyyy年MM月dd日 hh:mm");//消息模板使用
        Date date = new Date();
        //String sTime = sdf.format(date);
        //String ssTime = sdf.format(date);
        String creation = ssdf.format(date);

        // String seTime = sdf.format(date);
        Coupon couponData = new Coupon();
        couponData.setCode(code);
        couponData.setMoney(couponType.getMoney());
        couponData.setOriginal(couponType.getOriginal());
        couponData.setDateend(couponType.getDateend());
        couponData.setDatebeg(couponType.getDatebeg());
        couponData.setVipCode(phone);
        couponData.setType("VOU5");
        couponData.setScene(scene);
        couponData.setName(couponType.getName());
        couponData.setAccount(token);
        couponData.setToken(token);
        couponData.setCreation(creation);
        String source = "生日礼券";
        couponData.setSource(source);

        appCouponMapper.addCoupon(couponData);

        //保存生日领取记录
        BirthdayCouponRecord birthdayCouponRecord = new BirthdayCouponRecord();
        birthdayCouponRecord.setToken(token);
        birthdayCouponRecord.setUid(uid);
        birthdayCouponRecord.setBirthdayCouponId(cid);
        birthdayCouponMapper.addBirthdayCouponRecord(birthdayCouponRecord);

        if (!"1".equals(scene)) {
            try {
                Info info = GetInfo(token);
                CreateAppCoupon createAppCoupon = new CreateAppCoupon(info.getUrl(), info.getAccount(), info.getPassword());


                String objid = createAppCoupon.getData(code, couponType.getMoney(), phone,
                        couponType.getOriginal(), couponType.getDatebeg(), couponType.getDateend(),
                        goodsCode,storeCode);

            } catch (Exception e) {
                e.printStackTrace();
                throw new ErrorDataExceptionApp("出现错误,稍后重试");
            }
        }

        appCouponMapper.createIndexCouponRecord(cid, uid, token);
        //发送消息
        Coupon coupon = new Coupon();
        coupon.setName("满" + couponType.getOriginal() + "元减" + couponType.getMoney() + "优惠券");
        coupon.setDateend(creation);
        coupon.setCreation(creation);
        coupon.setVipCode(phone);
        appTemplateService.SendExchangeCoupon(coupon, phone, openid, token);
    }

    private Info GetInfo(String token) {
        return accountMapper.GetTokenData(token);
    }

    private static String create_nonce_str() {
        return UUID.randomUUID().toString();
    }

}
